<?php


namespace Hlcreation\Services;
use Illuminate\Support\Facades\Cache;

class CacheServices
{
    protected static $CacheType = 'redis';
    protected static $target = '_123321';

    public static function setTarget($target){
        self::$target = $target;
    }

    public static function handle()
    {

        return Cache::store(self::$CacheType)->tags([self::$target]);

    }


    /** 有限期内存储
     * @param $key key
     * @param $value 缓存值
     * @param int $time 有效期
     */
    public static function set($key, $value, $time = 172800){
        self::handle()->put($key, $value, $time);

    }

    /** 永久缓存数据
     * @param $key key 值
     * @param $value 缓存值
     */
    public static function forever($key, $value){
        self::handle()->forever($key, $value);
    }

    /** 获取缓存数据
     * @param $key  key值
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function get($key){
       return  self::handle()->get($key);
    }

    /** 获取缓存值，若缓存不存在，则将value 值存入缓存
     * @param $key key 值
     * @param $second  有效期
     * @param $value    缓存不存在，则将value 值存入缓存
     * @return mixed 返回缓存中的数据
     */
    public static function remember($key, $second, $callback){
        return  self::handle()->remember($key, $second, function () use ($callback){
            return is_callable($callback) ? $callback() : $callback;
        });
    }


    /** 获取不到缓存的话，将会把value值存入缓存 (永久缓存)
     * @param $key key 值
     * @param $second  有效期
     * @param $value    缓存不存在，则将value 值存入缓存
     * @return mixed 返回缓存中的数据
     */
    public static function rememberForever($key, $callback){
        $value =  self::handle()->rememberForever($key, function () use ($callback) {
            return is_callable($callback) ? $callback() : $callback;
        });
        return $value;
    }

    /** 判断缓存是否存在
     * @param $key
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function has($key){
        return self::handle()->has($key);
    }



    // 获取数据并删除该数据
    public static function pull($key){
        return self::handle()->pull($key);
    }

    // 删除该数据
    public static function delete($key){
        return self::handle()->forget($key);
    }

    // 清空所有数据
    public static function flush(){
        return self::handle()->flush();
    }
}
